<script>
import { defineComponent, computed, ref, watch } from 'vue';
import { createNamespace, transformSize } from '../utils';

export default defineComponent({
  name: createNamespace('Switch')[0],
  options: {
    // https://uniapp.dcloud.io/matter.html#mp
    virtualHost: true,
  },
  emits: ['update:modelValue', 'change'],
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    color: {
      type: String,
      default: '#04BE02',
    },
    size: {
      type: [String, Number],
      default: 30,
    },
  },
  setup(props, { emit }) {
    const innerShow = ref(props.modelValue);

    watch(
      () => props.modelValue,
      (val) => (innerShow.value = val),
    );

    const theStyle = computed(() => {
      const { size, color } = props;
      const s = `font-size: ${transformSize(
        size,
      )};--fan-switch--color: ${color};`;
      return s;
    });

    const onClick = () => {
      if (props.disabled) return;
      innerShow.value = innerShow.value ? false : true;
      emit('update:modelValue', innerShow.value);
      emit('change', innerShow.value);
    };

    return { innerShow, theStyle, onClick };
  },
});
</script>

<template>
  <div class="fan-switch" :class="[{ 'fan-switch__on': innerShow }, { 'fan-switch__d': disabled }]" @click="onClick"
    :style="theStyle">
    <div class="fan-switch__node"></div>
  </div>
</template>

<style lang="less">
.fan-switch {
  position: relative;
  width: calc(1.8em + 4px);
  height: calc(1em + 4px);
  background: rgba(120, 120, 128, 0.16);
  border-radius: 1em;
  cursor: pointer;
  transition: background 0.3s;
  display: inline-block;

  &__node {
    position: absolute;
    top: 2px;
    left: 2px;
    width: 1em;
    height: 1em;
    background-color: #fff;
    border-radius: 50%;
    box-shadow: 0 3px 1px 0 rgba(0, 0, 0, 0.05);
    transition: transform 0.3s cubic-bezier(0.3, 1.05, 0.4, 1.05);
  }

  &__d {
    opacity: var(--fan-disabled-opacity);
    cursor: not-allowed;
  }

  &__on {
    background: var(--fan-switch--color);

    .fan-switch__node {
      transform: translate(0.8em);
    }
  }
}
</style>
